package com.lenovo.hawk.aop;

import com.lenovo.hawk.config.DataSourceHolder;
import com.lenovo.hawk.constant.TargetDataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 动态数据源切换处理器
 * @author Hsg
 * @date    2020/07/17
 */
@Aspect
@Order(-1)  // 该切面应当先于 @Transactional 执行
@Component
@Slf4j
public class DynamicDataSourceAspect {

    /**
     * 切换数据源
     * @param point
     * @param dataSource
     */
    @Before("execution(* com.lenovo.hawk.service..*.*(..)) && @annotation(com.lenovo.hawk.constant.TargetDataSource) && @annotation(dataSource))")
    public void switchDataSource(JoinPoint point, TargetDataSource dataSource) {
        if (!DataSourceHolder.containDataSourceKey(dataSource.value())) {
            log.info("DataSource [{}] doesn't exist, use default DataSource [{}] " ,  dataSource.value());
        } else {
            // 切换数据源
            DataSourceHolder.setDataSource(dataSource.value());
            log.info("Switch DataSource to [{}] in Method [{}]",DataSourceHolder.getDataSource(),point.getSignature());
        }
    }

    /**
     * 重置数据源
     * @param point
     * @param dataSource
     */
    @After("@annotation(dataSource))")
    public void restoreDataSource(JoinPoint point, TargetDataSource dataSource) {
        // 将数据源置为默认数据源
        DataSourceHolder.clearDataSource();
        log.info("Restore DataSource to [{}] in Method [{}]" , DataSourceHolder.getDataSource(),point.getSignature());
    }
}